// imageUtils.js
import { fabric } from 'fabric';
import { calculatePolygonBounds } from './geomUtils';

// 根据图像大小计算canvas缩放的比例
function calcInitZoom(canvas_size, img_size) {
    // console.log(`canvas_size=`, canvas_size);
    // console.log(`img_size=`, img_size);
    let scalex = canvas_size.width / img_size.width;
    let scaley = canvas_size.height / img_size.height;
    let zoom = 1.0;
    if (scalex >= 1 && scaley >= 1) {
        zoom = 1.0;
    } else {
        zoom = scalex < scaley ? scalex - 0.01 : scaley - 0.01;
    }
    return zoom;
}

// 从canvas的坐标系转换到图像的坐标
// canvas coords => image coords
function getImageCoords(image, pts) {
    // console.log(`getImageCoords pts = `, pts);
    let new_pts = [];
    for (let i = 0; i < pts.length; i++) {
        let pt = pts[i];
        let real_left = image.left - image.width / 2;
        let real_top = image.top - image.height / 2;
        let img_x = pt.x - real_left;
        let img_y = pt.y - real_top;
        let new_pt = { x: img_x, y: img_y };
        new_pts.push(new_pt);
    }
    // console.log('getImageCoords new_pts = ', new_pts);
    return new_pts;
}

// 从图像坐标系转换到canvas坐标系
// image coords => canvas coords
function getCanvasCoords(image, pts) {
    // console.log('getCanvasCoords pts = ', pts);
    if (!image) {
        return [];
    }

    let new_pts = [];
    for (let i = 0; i < pts.length; i++) {
        let pt = pts[i];
        let real_left = image.left - image.width / 2;
        let real_top = image.top - image.height / 2;
        let canvas_x = pt.x + real_left;
        let canvas_y = pt.y + real_top;
        let new_pt = { x: canvas_x, y: canvas_y };
        new_pts.push(new_pt);
    }
    return new_pts;
}

// 限制pointer在image范围内
function limitPointerInImage(image, pointer) {
    let p0 = { x: 0, y: 0 };
    let p1 = { x: image.width, y: image.height };
    const tps = getCanvasCoords(image, [p0, p1]);

    // 限制鼠标不要超出图像的范围
    if (pointer.x < tps[0].x) {
        pointer.x = tps[0].x;
    }
    if (pointer.y < tps[0].y) {
        pointer.y = tps[0].y;
    }
    if (pointer.x > tps[1].x) {
        pointer.x = tps[1].x;
    }
    if (pointer.y > tps[1].y) {
        pointer.y = tps[1].y;
    }

    return true;
}

function getImageBase64ByRect(canvas, rect) {
    // 将截取的图像转换为base64编码
    let p1 = fabric.util.transformPoint({ x: rect.left, y: rect.top }, canvas.viewportTransform);
    let p2 = fabric.util.transformPoint({ x: rect.left + rect.width, y: rect.top + rect.height }, canvas.viewportTransform);
    const dataURL = canvas.toDataURL({
        format: 'jpeg',
        quality: 1,
        left: p1.x,
        top: p1.y,
        width: p2.x - p1.x,
        height: p2.y - p1.y
    });
    // console.log(dataURL);
    let base64Content = dataURL.match(/,(.*)$/)[1];
    return base64Content;
}

function getImageBase64ByPolygon(canvas, polygon) {
    let vpt = canvas.viewportTransform;
    let bounds = calculatePolygonBounds(polygon.points);
    let lt_pt = fabric.util.transformPoint({ x: bounds.left, y: bounds.top }, vpt);
    let rb_pt = fabric.util.transformPoint({ x: bounds.right, y: bounds.bottom }, vpt);
    let real_width = rb_pt.x - lt_pt.x;
    let real_height = rb_pt.y - lt_pt.y;

    // 创建临时canvas1
    var tempCanvas1 = document.createElement('canvas');
    tempCanvas1.width = canvas.width;
    tempCanvas1.height = canvas.height;
    var tempCtx1 = tempCanvas1.getContext('2d');

    // 创建裁剪路径
    tempCtx1.beginPath();
    let p = fabric.util.transformPoint(polygon.points[0], vpt);
    tempCtx1.moveTo(p.x, p.y);
    for (let i = 1; i < polygon.points.length; i++) {
        p = fabric.util.transformPoint(polygon.points[i], vpt);
        tempCtx1.lineTo(p.x, p.y);
    }
    tempCtx1.closePath();
    tempCtx1.clip();

    // 在临时canvas上绘制canvas1的内容
    tempCtx1.drawImage(canvas.getElement(), 0, 0, canvas.width, canvas.height);

    // 创建临时canvas2
    var tempCanvas2 = document.createElement('canvas');
    tempCanvas2.width = real_width;
    tempCanvas2.height = real_height;
    var tempCtx2 = tempCanvas2.getContext('2d');
    tempCtx2.drawImage(tempCanvas1, lt_pt.x, lt_pt.y, real_width, real_height, 0, 0, real_width, real_height);

    // 导出临时canvas的内容
    var dataURL = tempCanvas2.toDataURL();
    // console.log(dataURL);
    let base64Content = dataURL.match(/,(.*)$/)[1];
    return base64Content;
}

export { calcInitZoom, getImageCoords, getCanvasCoords, getImageBase64ByRect, getImageBase64ByPolygon, limitPointerInImage };
